import { useCallback, useEffect, useMemo, useState } from 'react';
import {confirm} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Modal, Tabs, Row, Col, Form, Tag, Input, InputNumber } from 'antd';
import { getMessage, TextWidget } from '@inbiz/react';
import { InbizIcon, getQueryString } from '@inbiz/utils';
import ColorInput from '../ColorInput';

// IconJson
import inbiz_btn from './IconJson/inbiz_btn.json';
import inbiz_component from './IconJson/inbiz_component.json';
import inbiz_menu from './IconJson/inbiz_menu.json';
import inbiz_navigat from './IconJson/inbiz_navigat.json';
import changeTitles from './changeTitle.json';
import icons from './IconJson/iconfont.json';

// component
import CustomIcon from './CustomIcon/index';
import IconTabPanContent from './IconTabPanContent';

// type
import { IconGroupType } from './service';
import { IIconItem } from './IconTabPanContent';
import './index.less';

interface IconType {
  type?: string;
  color?: string;
  size?: string | number;
  group?: IconGroupType;
  [key: string]: any;
}
type IconJson = {
  icon_id: string;
  name: string;
  font_class: string;
  unicode: string;
  unicode_decimal: number;
}[];
type IProps = {
  value?: IconType;
  defaultValue?: IconType;
  onChange?: (v: any) => void;
  onCancel: () => void;
  onOk: (val: any) => void;
  // 控制颜色选择的显影状态
  showColorPicker?: boolean;
  // 控制图标大小的显影状态
  showIconSize?: boolean;
  // 需要的格式（目前只有分组和单个图标格式）
  needType?: 'group';
  visible?: boolean;
  // 可通过传参控制图标选择的分组类型、搜索框显隐、图标title显隐
  showIconGroup?: Array<string>;
  isHideSearch?: boolean;
  isHideTitle?: boolean;
};

const { TabPane } = Tabs;
const IconPickerModal = (props: IProps) => {
  const { onChange, onOk, onCancel, visible, value, needType, showColorPicker, showIconSize, showIconGroup,isHideSearch,isHideTitle } = props;
  if (!visible) return null;
  // 选择颜色部分
  const [form] = Form.useForm();
  // 图标的数据
  const [selected, setSelected] = useState(value?.type || '');
  // 当前选项卡
  const [currentTab, setCurrentTab] = useState(needType !== 'group' ? 'tabMenuIcon' : 'tabCustomIcon');
  // 搜索的数据(serchValue记录当前搜索框的值，nowSerchvalue用于记录上一次搜索的数据)
  const [serchValue, setSerchValue] = useState('');
  const [nowSerchValue, setNowSerchValue] = useState('');
  // 自定义图标是否显示颜色标识(默认显示，不能影响其他)
  const [customIconShowColor, setCustomIconShowColor] = useState(true);
  // 图标分组
  const [checkSelectGroup, setCheckSelectGroup] = useState<IconGroupType>({
    Id: '',
    AppId: '',
    OutId: '',
    Name: '',
    IsDefault: false,
  });

  const [iconVal, setIconVal] = useState({});
  useEffect(() => {
    form.setFieldsValue({
      color: value?.color || '#000',
      size: value?.size || 24,
    });
  }, [])

  useEffect(() => {
    if (!value) return;
    if (value?.type) {
      setSelected(value?.type);
    }
    setIconVal({
      color: value?.color || '#000',
      size: value?.size || 24,
      ...value,
    });
  }, [value]);

  useEffect(() => {
    if (value?.group) {
      setCheckSelectGroup(value?.group)
    }
  }, [value?.group])

  const changeTitle = useCallback((nowIcons: IconJson) => {
    const objKeys = Object.keys(changeTitles);
    return nowIcons.map((item) => {
      let target = '';
      if (
        objKeys.some((ele) => {
          ele === item.name && (target = changeTitles[ele]);
          return ele === item.name;
        })
      ) {
        item.name = target;
        return item;
      } else return item;
    });
  }, []);

  // 区分图标类型(整体数据在第一次时运行)
  const allIconData = useMemo(() => {
    let processIco = icons.glyphs.filter((item: IIconItem) =>
      item.font_class.includes('inbiz_process-'),
    ) as {
      font_class: string;
    }[];

    let otherIco: any = icons.glyphs.filter(
      (item: IIconItem) =>
        item.font_class.includes(process.env.NODE_ENV === 'production' ? 'inbiz_other-' : '') ||
        item.font_class.includes('inbiz_basic-'),
    ) as {
      font_class: string;
    }[];
    otherIco = changeTitle(otherIco);

    // 使用json版
    let menuIcon = changeTitle(inbiz_menu.glyphs);
    let navigationIcon = changeTitle(inbiz_navigat.glyphs);
    let btnIcon = changeTitle(inbiz_btn.glyphs);
    let componentIcon = changeTitle(inbiz_component.glyphs);
    return [menuIcon, processIco, otherIco, navigationIcon, btnIcon, componentIcon];
  }, []);

  // 所有icon数据
  const [menuIcon, processIco, otherIco, navigationIcon, btnIcon, componentIcon] = allIconData;
  // 分组tab
  const allTabsData = [
    {
      title: getMessage('IconPicker.menuIcon'),
      key: 'tabMenuIcon',
      data: menuIcon,
    },
    {
      title: getMessage('IconPicker.navigationIcon'),
      key: 'tabNavigationIcon',
      data: navigationIcon,
    },
    {
      title: getMessage('IconPicker.btnIcon'),
      key: 'tabBtnIcon',
      data: btnIcon,
    },
    {
      title: getMessage('IconPicker.processIco'),
      key: 'tabProcessIcon',
      data: processIco,
    },
    {
      title: getMessage('IconPicker.componentIcon'),
      key: 'tabComponentIcon',
      data: componentIcon,
    },
    {
      title: getMessage('IconPicker.otherIco'),
      key: 'tabOtherIcon',
      data: otherIco,
    },
  ];
  const newTabsData = allTabsData?.filter((it) => { return showIconGroup?.includes(it.key) })
  const tabsData = newTabsData?.length ? newTabsData : allTabsData
  const init = () => {
    // tab调整至tabMenuIcon,选中返还为value的选中
    setCurrentTab(needType !== 'group' ? 'tabMenuIcon' : 'tabCustomIcon');
    setSerchValue('');
    setNowSerchValue('');
  }

  const handleOk = () => {
    if (needType === 'group') {
      if (checkSelectGroup.Id.length === 0) {
        confirm({
          title: getMessage('IconPicker.tip'),
          icon: <ExclamationCircleOutlined style={{ color: 'orange' }} />,
          content: getMessage('IconPicker.pleaseSelectIconGroup') + '!',
          okText: getMessage('IconPicker.okText'),
          cancelText: getMessage('IconPicker.cancelText'),
          centered: true,
          cancelButtonProps: {
            style: { display: 'none' },
          },
          onOk() { },
        });
        return;
      } else {
        onChange?.({
          ...value,
          group: checkSelectGroup,
        });
        setCheckSelectGroup({
          Id: '',
          AppId: '',
          OutId: '',
          Name: '',
          IsDefault: false,
        });
        setCurrentTab(needType !== 'group' ? 'tabMenuIcon' : 'tabCustomIcon');
      }
    } else {
      if (checkSelectGroup.Id.length > 0) {
        confirm({
          title: getMessage('IconPicker.tip'),
          icon: <ExclamationCircleOutlined style={{ color: 'orange' }} />,
          content: getMessage('IconPicker.pleaseSelectSingleIcon') + '!',
          okText: getMessage('IconPicker.okText'),
          cancelText: getMessage('IconPicker.cancelText'),
          centered: true,
          cancelButtonProps: {
            style: { display: 'none' },
          },
          onOk() { },
        });
        return;
      }
      form
        .validateFields()
        .then((values) => {
          const opt = { ...values, type: selected ? selected : value?.type }
          if (onOk) {
            onOk(opt);
            return;
          }
          onChange?.(opt);
          init();
        })
        .catch((err) => {
          console.log(err);
        });
    }
  };

  const handleCancel = () => {
    init();
    onCancel()
  }

  const handleChange = (val: string) => {
    setCurrentTab(val);
  };
  const handlePicker = (val: string, flag?: boolean) => {
    setCustomIconShowColor(!(flag === false));
    setSelected(val);
  };

  // 颜色选择部分的事件
  const onFinish = (values: any) => {
    setIconVal(values);
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  // 搜索框事件
  const serchValueChange = (e: any) => {
    setSerchValue(e.target.value);
    if (!e.target.value || e.target.value?.length < 1) {
      setNowSerchValue('');
    }
  };
  const onSearch = (value: string) => {
    setNowSerchValue(value?.trim());
  };
  // 搜索图标
  const serchIcon = (
    <Input.Search
      value={serchValue}
      placeholder={getMessage('IconPicker.searchIcon')}
      onChange={serchValueChange}
      onSearch={onSearch}
    />
  );

  const isVsCode = getQueryString('state') === 'code';

  return (
    <Modal
      className="iconModal"
      title={<TextWidget>IconPicker.iconSelect</TextWidget>}
      width={956}
      visible={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      okText={getMessage('IconPicker.okText')}
      cancelText={getMessage('IconPicker.cancelText')}
      destroyOnClose
    >
      <Tabs
        onChange={handleChange}
        defaultActiveKey={needType !== 'group' ? 'tabMenuIcon' : 'tabCustomIcon'}
        tabBarExtraContent={isHideSearch?'':serchIcon}
      >
        {needType !== 'group' &&
          tabsData.map((item) => {
            return (
              <TabPane
                tab={item.title}
                key={item.key}
                style={{
                  height:showIconGroup?.length? 282:375,
                  overflow: 'hidden',
                }}
              >
                <IconTabPanContent
                  allItems={item.data as any}
                  selected={selected}
                  serchValue={nowSerchValue}
                  handlePicker={handlePicker}
                  currentTab={currentTab}
                  isHideTitle={isHideTitle}
                  showIconGroup={showIconGroup}
                />
              </TabPane>
            );
          })}
        {(showIconGroup?.includes('tabCustomIcon')||showIconGroup?.length==0)&&<TabPane
          tab={getMessage('IconPicker.customIcon')}
          key="tabCustomIcon"
          style={{
            height:showIconGroup?.length? 282:370,
            overflowX: 'hidden',
            overflowY: 'auto',
            border: '1px solid #ddd',
            borderRadius: '4px',
            marginBottom: 5,
            padding: 10,
            transform: 'translateZ(0)',
          }}
        >
          <CustomIcon
            selected={selected}
            serchValue={nowSerchValue}
            setNowSerchValue={setNowSerchValue}
            setSerchValue={setSerchValue}
            checkSelectGroup={checkSelectGroup}
            setCheckSelectGroup={setCheckSelectGroup}
            handlePicker={handlePicker}
            isHideTitle={isHideTitle}
          ></CustomIcon>
        </TabPane>}
      </Tabs>

      <Row>
        <Col span={24}>
          {
            selected && (
              <div className="showChoseIcon">
                <span style={{ marginRight: 17 }}>
                  <TextWidget>IconPicker.icon</TextWidget>
                </span>
                {selected?.indexOf('/') === -1 && selected?.length > 1 ? (
                  <>
                    <div className={'choseIcon'}>
                      <InbizIcon type={selected} style={{ fontSize: 21 }} />
                    </div>
                    <span className="choseIconText">{selected}</span>
                  </>
                ) : (
                  <>
                    <div className={'choseIcon'}>
                      <InbizIcon type={selected} style={{ fontSize: 21 }} />
                    </div>
                    <span>{selected?.split('/')[selected.split('/')?.length - 1]}</span>
                  </>
                )}
              </div>
            )
          }
        </Col>
      </Row>
      <Row>
        <Col span={18}>
          <Form
            preserve={false}
            form={form}
            style={{ width: '100%' }}
            name="basic"
            initialValues={iconVal}
            onFinish={onFinish}
            onValuesChange={(changedValues) => {
              let opt = { ...iconVal, ...changedValues };
              form.setFieldsValue(opt);
              setIconVal(opt);
            }}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Row>
              {(showColorPicker === false ? false : true) &&
                componentIcon.filter((item: any) => {
                  return 'icon-' + item.font_class === selected;
                }).length === 0 &&
                (selected?.indexOf('/') === -1 || selected?.indexOf('.svg') > -1) &&
                selected &&
                customIconShowColor && (
                  <Col span={12} style={{ marginRight: 50 }}>
                    <Form.Item label={<TextWidget>IconPicker.color</TextWidget>} name="color">
                      <ColorInput isPicker={!isVsCode} />
                    </Form.Item>
                  </Col>
                )}
              {(showIconSize === false ? false : true) && selected && (
                <Col>
                  <Form.Item label={<TextWidget>IconPicker.size</TextWidget>} name="size">
                    <InputNumber className="sizeInput" min={12} max={72} step={1} precision={0} />
                  </Form.Item>
                </Col>
              )}
            </Row>
          </Form>
        </Col>
      </Row>
    </Modal>
  );
};

export default IconPickerModal;
